/*
 * Copyright (c) 2020 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "nativeapi_communication_kit_impl.h"
#include <ctype.h>
#include <dirent.h>
#include <fcntl.h>
#include <limits.h>
#include <securec.h>
#include <stdbool.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "nativeapi_config.h"
#if (defined _WIN32 || defined _WIN64)
#include "shlwapi.h"
#endif

static JsCallClangFunctionDef g_jsGetClang = NULL;
static JsCallClangFunctionDef g_jsSetClang = NULL;

static bool IsValidValue(const char *value)
{
    if (value == NULL)
    {
        return false;
    }
    size_t valueLen = strnlen(value, VALUE_MAX_LEN + 1);
    if ((valueLen == 0) || (valueLen > VALUE_MAX_LEN))
    {
        return false;
    }
    return true;
}

int GetCommunicationKitValue(const char *key, char *value)
{
    if ((key == NULL) || (value == NULL))
    {
        return ERROR_CODE_PARAM;
    }
    if (NULL != g_jsGetClang)
    {
        if (0 != g_jsGetClang(key, value))
        {
            LOG_E("g_jsGetClang error!\r\n");
        }
    }
    else
    {
        LOG_I("If you want use js get c interface, you should use JsGetClangFuncationRegister function.\r\n");
    }
    return NATIVE_SUCCESS;
}

int SetCommunicationKitValue(const char *key, const char *value)
{
    if ((key == NULL) || (!IsValidValue(value)))
    {
        return ERROR_CODE_PARAM;
    }
    if (NULL != g_jsSetClang)
    {
        if (0 != g_jsSetClang(key, value))
        {
            LOG_E("g_jsSetClang error!\r\n");
        }
        LOG_I("CommunicationKit:SetJsonValue::entry--key=%s;value=%s.\r\n", key, value);
    }
    else
    {
        LOG_I("If you want use js set c interface, you should use JsSetClangFuncationRegister function.\r\n");
    }
    return NATIVE_SUCCESS;
}

void JsGetClangFuncationRegister(JsCallClangFunctionDef jsGetClang)
{
    g_jsGetClang = jsGetClang;
}
void JsSetClangFuncationRegister(JsCallClangFunctionDef jsSetClang)
{
    g_jsSetClang = jsSetClang;
}

void JsGetClangFuncationUnregister(void)
{
    g_jsGetClang = NULL;
}
void JsSetClangFuncationUnregister(void)
{
    g_jsSetClang = NULL;
}